import React, { Component } from 'react';
import { nanoid } from 'nanoid'

import { Dropdown, Button, Menu } from 'antd'
import { DownOutlined } from '@ant-design/icons'

import { arrToObj } from '@/utils/utils'

import './style.scss'

interface nav_type {
  id:string,
  name:string,
  type:number
}

interface time_type {
  id:string,
  name:string,
  value:number
}

interface Props_type {
  updateSearch:Function
}

class Sort extends Component<Props_type> {

  state = {
    navList:[
      {
        id:nanoid(),
        name:'热门',
        type:1,
        value:'xxx'
      },
      {
        id:nanoid(),
        name:'最新',
        type:2
      },
      {
        id:nanoid(),
        name:'热榜',
        type:3
      }
    ],
    currentNav:1,
    timeList:[
      {
        id:nanoid(),
        name:'3天内',
        value:1
      },
      {
        id:nanoid(),
        name:'7天内',
        value:2
      },
      {
        id:nanoid(),
        name:'30天内',
        value:3
      },
      {
        id:nanoid(),
        name:'全部',
        value:0
      }
    ],
    currentTime:1
  }

  /**
   * 点击排序
   * @param nav 
   */
  handleSort = (nav:nav_type) => {
    this.setState({currentNav:nav.type})
    this.props.updateSearch({type:2,time:3})
  }

  // 选择时间排序
  handleMenuClick = (e:any) => {
    this.setState({currentTime:Number(e.key)})
  }

  render() {
    const { navList, currentNav, timeList, currentTime } = this.state
    const currentTimeObj = arrToObj(timeList,'value','name')

    // 选择时间的列表
    const timeMenu = (
      <Menu onClick={ this.handleMenuClick } >
        {
          timeList.map( (item:time_type) => (
            <Menu.Item key={item.value} style={{color:'#909090'}}>
              {item.name}
            </Menu.Item>
          ))
        }
      </Menu>
    )

    return (
      <header className="sort">
        <nav className="list-nav">
          <ul className="nav-list">
            {
              navList.map( (nav:nav_type) => (
                <li key={ nav.id } 
                    onClick={ () => this.handleSort(nav) }
                    className={ nav.type === currentNav ? "nav-item active" : 'nav-item'}>
                  {nav.name}
                </li>
              ))
            }
          </ul>
          {
            currentNav === 3
            ? (
              <div className="dorp-down-area">
                <Dropdown overlay={timeMenu} trigger={['click']}>
                  <Button>
                    {currentTimeObj[currentTime]} <DownOutlined />
                  </Button>
                </Dropdown>
              </div>
            )
            : null
          }
        </nav>
      </header>
    );
  }
}

export default Sort;